//
//  NSAttributedString+ZLExtensions.swift
//  ZLUIKit_Example
//
//  Created by itzhaolei on 2021/8/26.
//  Copyright © 2021 CocoaPods. All rights reserved.
//

import UIKit

public extension NSAttributedString {
        
    /// 统一样式的富文本内容初始化
    convenience init?(string: String, font: UIFont, foregroundColor: UIColor, alignment: NSTextAlignment, lineSpacing: CGFloat, kern: CGFloat) {
        if string.isEmpty || string.count < 1 {
             return nil
        }
        let paragraphStyle: NSMutableParagraphStyle = .init()
        if lineSpacing != 0 || alignment != .left {
             paragraphStyle.lineSpacing = lineSpacing
             paragraphStyle.alignment = alignment
        }
        self.init(string: string, attributes: [.font: font, .foregroundColor: foregroundColor, .kern: kern, .paragraphStyle: paragraphStyle])
    }
    
    
    enum Target {
        case size, width, height
    }
    /// 计算富文本尺寸值
    /// - Parameters:
    ///   - target: 要获取的目标，该目标一定要Returns返回的使用价值相对应
    ///   - limit: 限制条件：例如想要获取宽的值，就填写对高的限制，依次类推
    /// - Returns: 处理下文
    func getSize(target: Target, limit: CGFloat = CGFloat(MAXFLOAT)) -> CGSize {
        var limitSize: CGSize? = nil
        if target == .width {
            limitSize = .init(width: CGFloat(MAXFLOAT), height: limit)
        }else if (target == .height) {
            limitSize = .init(width: limit, height: CGFloat(MAXFLOAT))
        }else {
            limitSize = .init(width: CGFloat(MAXFLOAT), height: CGFloat(MAXFLOAT))
        }
        let label = UILabel(frame: .init(x: 0, y: 0, width: limitSize?.width ?? 0, height: limitSize?.height ?? 0))
        label.numberOfLines = 0
        label.attributedText = self
        label.lineBreakMode = .byTruncatingTail
        label.sizeToFit()
        return label.frame.size
    }
    
}
